/**
 * 项目入口文件
 * 灵犀指引 - Spiritual Insight Guidance
 */

// 加载环境变量
require('dotenv').config();

// 引入Express框架
const express = require('express');
const cors = require('cors');
const helmet = require('helmet');
const { logInfo, logError, logWarning } = require('./logger');

// 数据库初始化
const { initDatabase } = require('./models/User');
const { initMongoDB } = require('./config/mongoConfig');

// 引入路由
const userRoutes = require('./routes/user.routes');
const divinationRoutes = require('./routes/divination.routes');
const dreamRoutes = require('./routes/dream.routes');
const uploadRoutes = require('./routes/upload.routes');
const paymentRoutes = require('./routes/payment.routes');
const subscriptionRoutes = require('./routes/subscription.routes');
const nameAnalysisRoutes = require('./routes/nameAnalysis.routes');
const faceAnalysisRoutes = require('./routes/faceAnalysis.routes');
const palmAnalysisRoutes = require('./routes/palmAnalysis.routes');
const adminRoutes = require('./admin');

// 创建Express应用
const app = express();
const PORT = process.env.PORT || 3002;

// 中间件
app.use(helmet()); // 安全头部
app.use(cors()); // 跨域支持
app.use(express.json({ limit: '10mb' })); // JSON解析
app.use(express.urlencoded({ extended: true, limit: '10mb' })); // URL编码解析
app.use('/uploads', express.static('uploads')); // 静态文件服务
app.use(express.static('frontend/build')); // 提供前端构建文件

app.get('/health', (req, res) => {
  res.status(200).json({ 
    status: 'OK', 
    timestamp: new Date().toISOString(),
    uptime: process.uptime()
  });
});

// 前端页面路由
app.get('/', (req, res) => {
  res.sendFile(__dirname + '/../frontend/build/index.html');
});

// 确保所有其他未匹配的路由都返回前端index.html（支持前端路由）
app.get('*', (req, res, next) => {
  // 排除API路由、健康检查路由和后台管理路由
  if (req.path.startsWith('/api/') || req.path === '/health' || req.path.startsWith('/admin')) {
    next();
    return;
  }
  res.sendFile(__dirname + '/../frontend/build/index.html');
});

// 后台管理路由
app.use('/admin', adminRoutes);

// API路由
app.use('/api/users', userRoutes);
app.use('/api/divination', divinationRoutes);
app.use('/api/dreams', dreamRoutes);
app.use('/api/upload', uploadRoutes);
app.use('/api/payments', paymentRoutes);
app.use('/api/subscriptions', subscriptionRoutes);
app.use('/api/name-analysis', nameAnalysisRoutes);
app.use('/api/face-analysis', faceAnalysisRoutes);
app.use('/api/palm-analysis', palmAnalysisRoutes);

// 错误处理中间件
app.use((err, req, res, next) => {
  // 使用日志模块记录错误
  logError('全局错误处理', {
    error: err.message,
    stack: err.stack,
    url: req.url,
    method: req.method,
    user: req.user ? req.user.username : 'anonymous'
  });
  
  // 统一错误响应格式
  const statusCode = err.statusCode || 500;
  const errorType = err.error || 'InternalServerError';
  
  res.status(statusCode).json({
    error: errorType,
    message: process.env.NODE_ENV === 'development' || err.expose ? err.message : '服务器遇到了一个意外错误',
    // 在开发环境下提供更多信息
    ...(process.env.NODE_ENV === 'development' && {
      details: {
        stack: err.stack,
        originalError: err.originalError
      }
    })
  });
});

// 404处理
app.use((req, res) => {
  logWarning('404 Not Found', {
    url: req.url,
    method: req.method,
    ip: req.ip,
    user: req.user ? req.user.username : 'anonymous'
  });
  
  res.status(404).json({
    error: 'NotFound',
    message: '请求的资源不存在',
    path: req.url,
    method: req.method
  });
});

// 初始化数据库
const { testConnection } = require('./config/database');

// 启动服务器
// 启动服务器
async function startServer() {
  try {
    console.log('开始启动服务器...');
    console.log(`配置的端口: ${PORT}`);
    
    // 初始化MySQL数据库
    console.log('尝试连接MySQL数据库...');
    await testConnection();
    console.log('✅ MySQL数据库连接成功');
    
    // 暂时跳过MongoDB连接，直接启动HTTP服务
    console.log('⚠️  跳过MongoDB连接，直接启动HTTP服务（调试模式）');
    
    console.log('尝试启动HTTP服务器...');
    const server = app.listen(PORT, () => {
      console.log(`✅ 服务器成功启动在端口 ${PORT}`);
      console.log(`📡 健康检查: http://localhost:${PORT}/health`);
      console.log(`🌐 根路径: http://localhost:${PORT}/`);
    });

    // 优雅关闭
    process.on('SIGTERM', () => {
      console.log('收到 SIGTERM 信号，开始优雅关闭服务器');
      server.close(() => {
        console.log('服务器已成功关闭');
        process.exit(0);
      });
    });

    process.on('SIGINT', () => {
      console.log('收到 SIGINT 信号，开始优雅关闭服务器');
      server.close(() => {
        console.log('服务器已成功关闭');
        process.exit(0);
      });
    });
  } catch (error) {
    console.error('❌ 数据库连接失败:', error.message);
    process.exit(1);
  }
}

// 启动服务器
startServer();

// 处理未捕获的异常
process.on('uncaughtException', (err) => {
  console.error('未捕获的异常', {
    message: err.message,
    stack: err.stack
  });
  
  // 给一些时间让日志写入
  setTimeout(() => {
    process.exit(1);
  }, 1000);
});

// 处理未处理的Promise拒绝
process.on('unhandledRejection', (reason, promise) => {
  console.error('未处理的Promise拒绝', {
    reason: reason.message || reason,
    stack: reason.stack
  });
});